import { ref, h, onMounted, onUnmounted, reactive } from 'vue';
import { useMessage, useNotification, NImage, NEmpty } from 'naive-ui';
import { cancelOauthCode, getOauthCode, pollingOauth } from "@/api/wxmp/wxmp";
import { getWxmpQrCodeUrl } from "@/api/system/config";
import { formatToDateTime } from "@/utils/dateUtil";
import { ResultEnum } from "@/enums/httpEnum";

type WxOauthBusinessType = {
  name: string,
  type: string
}

type WxOauthBusinessConstantInterface = {
  [index: string]: WxOauthBusinessType
}

export const WxOauthBusinessConstant: WxOauthBusinessConstantInterface = {
  LOGIN: {
    name: '登录',
    type: 'login'
  },
  BIND: {
    name: '绑定',
    type: 'bind'
  },
  UNBIND: {
    name: '解绑',
    type: 'unbind'
  }
}

export function useWxOauth() {
  const message = useMessage();
  const notification = useNotification()

  const wxOauthQrcodeSrc = ref<string>()
  const wxOauthTimeout = ref<number | undefined>(undefined)
  const wxOauthNotificationInstance = ref()
  const meta = reactive<{business: null | WxOauthBusinessType, code: string | null}>({
    business: null,
    code: null
  })

  const handlerWxOauth = async (businessMeta: WxOauthBusinessType, successCb: Fn, errorCb?: Fn) => {
    if (wxOauthTimeout.value) {
      message.info("正在授权, 请勿重复点击")
      return
    }
    const code = await getOauthCode(businessMeta.type)
    meta.business = businessMeta
    meta.code = code
    wxOauthNotificationInstance.value = notification.create({
      title: `微信授权${businessMeta.name}`,
      description: (() => {
        return h('span', {
          style: {
            fontWeight: 'bold',
            fontSize: '13px'
          }
        }, {
          default: () => `请打开公众号后回复【${businessMeta.name}${code}】来进行${businessMeta.name}`
        })
      }),
      content: (() => {
        return wxOauthQrcodeSrc.value ?
          h(NImage, {
            src: wxOauthQrcodeSrc.value,
            previewDisabled: true
          }) :
          h(NEmpty, {
            size: 'huge'
          }, { default: () => '获取二维码失败，请联系管理员' })
      }),
      meta: formatToDateTime(new Date()),
      onAfterLeave: async () => {
        if (wxOauthTimeout.value) {
          window.clearInterval(wxOauthTimeout.value)
          wxOauthTimeout.value = undefined
          await cancelOauthCode(businessMeta.type, code)
          message.warning("已取消微信授权, 授权码失效")
        }
      }
    })
    wxOauthTimeout.value = window.setInterval(async () => {
      const response = await pollingOauth(businessMeta.type, code)
      const state = response.data;
      if (state === 'success') {
        window.clearInterval(wxOauthTimeout.value)
        wxOauthTimeout.value = undefined
        await successCb(response)
        wxOauthNotificationInstance.value?.destroy()
      }
      if (state === 'error') {
        if (errorCb && errorCb instanceof Function) {
          await errorCb()
        }
        message.error('授权失败, 请刷新重新获取授权码');
        window.clearInterval(wxOauthTimeout.value)
        wxOauthTimeout.value = undefined
        wxOauthNotificationInstance.value?.destroy()
      }
    }, 3 * 1000)
  }

  onMounted(async () => {
    getWxmpQrCodeUrl().then(res => {
      const { code, data } = res;
      if (code === ResultEnum.SUCCESS) {
        wxOauthQrcodeSrc.value = data;
      }
    })
  })

  onUnmounted(async () => {
    if (wxOauthTimeout.value) {
      window.clearInterval(wxOauthTimeout.value)
      wxOauthTimeout.value = undefined
      await cancelOauthCode(meta.business?.type, meta.code)
      wxOauthNotificationInstance.value?.destroy()
    }
  })

  return { wxOauthTimeout, wxOauthNotificationInstance, handlerWxOauth }
}


